import { useEffect, useMemo, useState } from "react"
import { useNav } from "../../../hooks/useNav"
import { useLocation } from "react-router-dom"
import {  Tabs } from "antd-mobile"
import './index.scss'
import { ShopHead } from "./components/ShopHead/ShopHead"
import { CommodityList } from "./components/CommodityList/CommodityList"
import { ShopCard } from "./components/ShopCard/ShopCard"
import { getShopCategory, getShopCommodity, getShopInfoOneAPI, type CategoryItem, type Commodity, type ShopItem } from "../../../api/shops"

import { Loading } from "../../../layouts/MainLayout/components/loading"




const ShopDetails = () => {
    const [changeTabs, setChangeTabs] = useState<string>('全部菜品') //tab 全部菜品，评价，商家
    // const [isLoading, setIsLoading] = useState<boolean>(false)   
    const [shopCategory, setShopCategory] = useState<CategoryItem[]>([])  //商家分类列表
    const [shopCommodity, setShopCommodity] = useState<Commodity[]>([])   //商家商品信息列表
    const [activeCategoryId, setActiveCategoryId] = useState<string>('')  //当前选中的商品分类id
    const [shopInfo, setShopInfo] = useState<ShopItem | undefined>()  //商家信息
    const location = useLocation()
    const searchParams = new URLSearchParams(location.search)
    const shops_id = searchParams.get('id') || ''

    //获取商家信息
    useEffect(() => {
        async function getShopInfoOne() {
            if (!shops_id) return
            try {
                const res = await getShopInfoOneAPI(shops_id)
                console.log(res.data)
                setShopInfo(res.data.data)
            } catch (error) {
                console.log(error + "商家信息获取错误")
            }
        }
        getShopInfoOne()
    }, [shops_id])
    //获取商家商品分类
    useEffect(() => {
        //根据id请求数据
        async function getCategory() {
            if (!shops_id) return
            // setIsLoading(true)
            try {
                const res = await getShopCategory(shops_id)
                console.log(res.data)
                setShopCategory(res.data.data)
                // setIsLoading(false)
            } catch (error) {
                console.log(error)
                // setIsLoading(false)
            }
        }
        getCategory()
    }, [shops_id, shopInfo])
    //  初始化首个分类ID（分类加载完成后自动设置）
    useEffect(() => {
        if (shopCategory.length > 0) {
            // 初始选中第一个分类
            setActiveCategoryId(shopCategory[0]._id)
        } else {
            // 分类为空时重置
            setActiveCategoryId('')
            setShopCommodity([])
        }
    }, [shopCategory]) // 依赖分类列表变化
    
    //动态监控分类选择
    useEffect(() => {
        //根据商品分类获取商品信息
    async function getCommodity(category_id: string) {
        if (!category_id || !shops_id) return
        try {
            const res = await getShopCommodity(shops_id, category_id)
            console.log(res.data)
            const commandList = res.data.data.map((item) => {
                return { ...item, count: 0 }
            })
            setShopCommodity(commandList || [])
        } catch (error) {
            console.log("商品信息获取失败" + error)
            setShopCommodity([])
        }
    }
        if (activeCategoryId) {
            getCommodity(activeCategoryId)
        }
    }, [activeCategoryId, shops_id])

    //缓存防止重新渲染然后重新传对象无限循环
    const navBar = useMemo(() => {
        return {
            backIcon: true,
            children: shopInfo?.title,
            back: ''
        }
    }, [shopInfo])
    useNav(navBar)
    // 校验所有必要数据是否存在
    const isDataReady = Boolean(shops_id && shopInfo && shopCommodity && shopCategory && activeCategoryId);
    function changeType(category_id: string) {
        setActiveCategoryId(category_id)
    }

console.log(shops_id , shopInfo, shopCommodity , shopCategory , activeCategoryId)
    if (!isDataReady) {
        return <Loading />
       
    }

    const tabs = [
        '全部菜品', '评价', '商家'
    ]

    const changeTab = (item: string) => {
        setChangeTabs(item)
    }



    return <div className="shopDeatils">
        {/* 商家信息头部 */}
        <ShopHead shopInfo={shopInfo} />


        {/* 切换tabs */}
        <Tabs className="tabs" onChange={changeTab}>
            {tabs.map(item => (
                <Tabs.Tab title={item} key={item} ></Tabs.Tab>
            ))}

        </Tabs>

        {
            changeTabs === '全部菜品' &&
            <>
                {/* 商品列表 */}
                < CommodityList shops_id={shops_id} shopCommodity={shopCommodity} activeCategoryId={activeCategoryId} changeType={changeType} shopCategory={shopCategory} />
                {/* 购物车 */}
                <ShopCard delivery_fee={shopInfo?.delivery_fee} shops_id={shops_id} />

            </>

        }

        {/* 其他 tabs 内容可在这里补充 */}
        {changeTabs === '评价' && <div>评价内容</div>}
        {changeTabs === '商家' && <div>商家详情</div>}



    </div>
}

export { ShopDetails }